<script setup lang="ts">
import { shallowRef, onMounted, watch, ref, reactive } from 'vue';
import { message } from 'ant-design-vue';
import axios, { type AxiosError } from 'axios';
import dayjs, { Dayjs } from 'dayjs';

interface IosTask {
  id: number;
  afkey: string;
  appid: string;
  appname: string;
  dwappid: string;
  jsname: string;
  name: string;
  state: number;
  version: string;
}

// 定义错误响应接口
interface ErrorResponse {
  message?: string;
}

// 表格列配置
const columns = shallowRef([
  {
    title: '应用名',
    dataIndex: 'appname',
    key: 'appname',
    width: 200
  },
  {
    title: '文件名',
    dataIndex: 'jsname',
    key: 'jsname'
  },
  {
    title: '应用包名',
    dataIndex: 'appid',
    key: 'appid'
  },
  {
    title: '应用id',
    dataIndex: 'dwappid',
    key: 'dwappid'
  },
  {
    title:'Key',
    dataIndex: 'afkey',
    key: 'afkey'
  },
  {
    title: '状态',
    dataIndex: 'state',
    key: 'state',
    customRender: ({ text }: { text: number }) => {
      return text === 1 ? '启用' : '禁用';
    }
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 150
  }
]);

const state = shallowRef({
  dataSource: [] as IosTask[],
  loading: false,
  pagination: {
    current: 1,
    pageSize: 999, // 每页显示999条数据
    total: 0,
    showSizeChanger: false,
    showTotal: (total: number) => {
      return `当前共 ${total} 条数据`;
    }
  }
});

const formState = reactive({
  formVisible: false,
  isUpdate: false,
  uploadVisible: false,
  formData: {
    appname: '',
    jsname: '',
    appid: '',
    dwappid: '',
    afkey: '',
    state: 1,
    version: ''
  } as Partial<IosTask>,
  uploadForm: {
    file: null,
    path: '',
    updateTime: undefined as Dayjs | undefined
  }
});

// 使用axios发送请求
const selectedState = ref<number | null>(1);

const fetchData = async () => {
  state.value.loading = true;
  try {
    console.log('[DEBUG] 请求参数:', { state: selectedState.value });
    const { data: result } = await axios.get('http://47.96.125.116:8088/iostask/selectAllIostask', {
      params: {
        state: null // 这里改为null，获取所有数据，前端自己过滤
      }
    });
    console.log('[DEBUG] 接口响应数据:', {
      params: { state: selectedState.value },
      response: result
    });

    const rawData = result?.resultMessage || [];

    if (!Array.isArray(rawData)) {
      throw new Error('接口返回数据格式不正确');
    }

    // 调试输出数据状态
    console.log('[DEBUG] 原始数据状态分布:',
        rawData.reduce((acc, item) => {
          acc[item.state] = (acc[item.state] || 0) + 1;
          return acc;
        }, {})
    );

    // 前端过滤逻辑
    const filteredData = selectedState.value !== null
        ? rawData.filter(item => item.state === selectedState.value)
        : rawData;

    console.log('[DEBUG] 过滤后数据:', {
      selectedState: selectedState.value,
      filteredCount: filteredData.length,
      sampleData: filteredData.slice(0, 3) // 打印前3条数据示例
    });

    const formattedData = filteredData.map(item => ({
      ...item,
      key: item.id || Math.random().toString(36).slice(2, 11)
    }));

    state.value = {
      ...state.value,
      dataSource: formattedData,
      pagination: {
        ...state.value.pagination,
        total: formattedData.length
      },
      loading: false
    };

  } catch (error) {
    console.error('[ERROR] 请求失败:', error);
    message.error(`数据加载失败: ${(error as AxiosError).message || '未知错误'}`);
    state.value.loading = false;
  }
};

const handleTableChange = (pagination: any) => {
  state.value.pagination.current = pagination.current;
};

watch(selectedState, () => {
  console.log('[WATCH] 选中状态变化:', selectedState.value);
  fetchData();
}, { immediate: true });

onMounted(() => {
  console.log('[INIT] 初始化加载数据...');
  fetchData();
});

const formRef = ref();

const openAdd = () => {
  formState.formVisible = true;
  formState.isUpdate = false;
  formState.formData = {
    appname: '',
    jsname: '',
    appid: '',
    dwappid: '',
    afkey: '',
    state: 1,
    version: ''
  };
};

// 编辑修改/添加操作
const handleFormSubmit = async () => {
  try {
    await formRef.value.validate();
    state.value.loading = true;
    const url = formState.isUpdate
        ? 'http://47.96.125.116:8088/iostask/updateIostask'
        : 'http://47.96.125.116:8088/iostask/insertIostask';
    await axios.get(url, { params: formState.formData });
    message.success(formState.isUpdate ? '更新成功' : '添加成功');
    formState.formVisible = false;
    await fetchData();
  } catch (error) {
    if (typeof error === 'object' && error !== null && 'errorFields' in error) {
      return message.error('请完善必填字段');
    }
    const err = error as AxiosError<ErrorResponse>;
    console.error('[ERROR] 提交失败:', err);
    message.error(`更新失败: ${err.response?.data?.message || err.message}`);
  } finally {
    state.value.loading = false;
  }
};

const handleEdit = (record: IosTask) => {
  formState.formVisible = true;
  formState.isUpdate = true;
  formState.formData = { ...record };
};

// 删除操作
const handleDelete = async (record: IosTask) => {
  try {
    await axios.get('http://47.96.125.116:8088/iostask/delIostask', {
      params: {
        id: record.id
      }
    });
    message.success('删除成功');
    await fetchData();
  } catch (error) {
    const err = error as AxiosError<ErrorResponse>;
    console.error('[ERROR] 删除失败:', err);
    message.error(`删除失败: ${err.response?.data?.message || err.message}`);
  }
};

const fileList = ref<any[]>([]);

const beforeUpload = (file) => {
  fileList.value = [...fileList.value, file];
  return false;
};

// 批量上传操作
const handleUploadSubmit = async () => {
  try {
    if (fileList.value.length > 10) {
      message.error('最多选择10个文件');
      return;
    }
    if (!fileList.value.length) {
      message.error('请选择上传文件');
      return;
    }
    if (!formState.uploadForm.path) {
      message.error('请填写存储路径');
      return;
    }

    const formData = new FormData();
    fileList.value.forEach(file => {
      formData.append('files', file.originFileObj);
    });
    formData.append('file_path', formState.uploadForm.path);
    if (formState.uploadForm.updateTime) {
      formData.append('update_time', dayjs(formState.uploadForm.updateTime).unix().toString());
    }

    await axios.post('http://47.96.125.116:8088/ascript_file/batch', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    message.success('批量上传成功');
    formState.uploadVisible = false;
    fileList.value = [];
    await fetchData();
  } catch (error) {
    const err = error as Error;
    console.error('上传失败:', err);
    message.error(`上传失败: ${err.message}`);
  }
};
</script>

<template>
  <a-card>
    <template #extra>
      <a-space>
        <div class="filter-bar" style="margin-right: 1200px">
          <a-radio-group v-model:value="selectedState" button-style="solid">
            <a-radio-button :value="1">启用</a-radio-button>
            <a-radio-button :value="0">禁用</a-radio-button>
            <a-radio-button :value="null">全部</a-radio-button>
          </a-radio-group>
        </div>
        <a-button type="primary" class="light-green-btn" @click="openAdd">
          添加任务
        </a-button>
        <a-button type="primary" @click="formState.uploadVisible = true">
          批量上传
        </a-button>
      </a-space>
    </template>

    <a-table
        row-key="key"
        :columns="columns"
        :data-source="state.dataSource"
        :pagination="state.pagination"
        :loading="state.loading"
        bordered
        @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <a-space>
            <a-button @click="handleEdit(record as IosTask)" size="small">编辑</a-button>
            <a-popconfirm
                title="确定删除？"
                @confirm="handleDelete(record as IosTask)"
            >
              <a-button type="link" danger size="small">删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>

      <template #emptyText>
        <div v-if="state.loading" class="loading-spinner">
          <a-spin /> 加载中...
        </div>
        <div v-else class="empty-tip">
          <a-empty description="暂无数据" />
        </div>
      </template>
    </a-table>

    <a-modal
        v-model:open="formState.formVisible"
        :title="formState.isUpdate ? '编辑配置' : '新建配置'"
        @ok="handleFormSubmit"
        @cancel="() => {
        formState.formVisible = false;
        formState.formData = {
          name: '',
          appname: '',
          jsname: '',
          appid: '',
          dwappid: '',
          afkey: '',
          state: 1,
          version: ''
        };
      }"
    >
      <!--弹出框表单-->
      <a-form
          ref="formRef"
          :model="formState.formData"
          :label-col="{ style: { width: '100px' } }"
          :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="ID" v-if="formState.isUpdate">
          <a-input v-model:value="formState.formData.id" disabled />
        </a-form-item>
        <a-form-item name="appname" label="应用名" :rules="[{ required: true, message: '请输入应用名' }]">
          <a-input v-model:value="formState.formData.appname" />
        </a-form-item>
        <a-form-item name="jsname" label="文件名" :rules="[{ required: true, message: '请输入文件名' }]">
          <a-input v-model:value="formState.formData.jsname" />
        </a-form-item>
        <a-form-item name="appid" label="应用包名" :rules="[{ required: true, message: '请输入应用包名' }]">
          <a-input v-model:value="formState.formData.appid" />
        </a-form-item>
        <a-form-item name="name" label="任务名称">
          <a-input v-model:value="formState.formData.name" />
        </a-form-item>
        <a-form-item label="应用ID">
          <a-input v-model:value="formState.formData.dwappid" />
        </a-form-item>
        <a-form-item label="版本">
          <a-input v-model:value="formState.formData.version" />
        </a-form-item>
        <a-form-item label="状态">
          <a-select v-model:value="formState.formData.state">
            <a-select-option :value="1">启用</a-select-option>
            <a-select-option :value="0">禁用</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="AF Key">
          <a-input v-model:value="formState.formData.afkey" />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal
        v-model:open="formState.uploadVisible"
        title="批量上传"
        @ok="handleUploadSubmit"
        @cancel="formState.uploadVisible = false"
        width="600px"
    >
      <a-form
          :label-col="{ style: { width: '100px' } }"
          :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="上传文件" required>
          <a-upload
              v-model:fileList="fileList"
              :before-upload="beforeUpload"
              accept=".py"
              :maxCount="10"
              multiple
          >
            <a-button>
              选择文件
            </a-button>
          </a-upload>
        </a-form-item>
        <a-form-item label="存储路径">
          <a-input
              v-model:value="formState.uploadForm.path"
              placeholder="请输入存储路径"
          />
        </a-form-item>
        <a-form-item label="更新时间">
          <a-date-picker
              v-model:value="formState.uploadForm.updateTime"
              show-time
              format="YYYY-MM-DD HH:mm"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<style scoped>
.loading-spinner {
  padding: 40px 0;
  text-align: center;
}
.empty-tip {
  padding: 20px 0;
}
:deep(.ant-table-thead > tr > th) {
  background-color: #fafafa;
}
/* 浅绿色按钮样式 */
.light-green-btn {
  background-color: #4caf50;
  border-color: #8bc34a;
  color: white;
}
.light-green-btn:hover,
.light-green-btn:focus {
  background-color: #45a049;
  border-color: #9dce5d;
  color: white;
}
</style>